const multer = require('multer')
const { uploadPath, uploadURL, maxFileSize } = require('../config')
const path = require('path')
const fs = require('fs')
const assert = require('http-assert')
const allUploadType = ['avatar', 'cover','navigation','article']
const tips = {
  avatar: '添加用户头像成功',
  cover: '添加文章封面成功',
  navigation: '添加导航图标成功',
  article: '添加文章图片成功',
}
const storage = multer.diskStorage({
  //存储位置
  destination(req, res, cb) {
    const uploadType = req.params.type || req.body.type
    const filePath = path.join(uploadPath, uploadType)
    fs.existsSync(filePath) || fs.mkdirSync(filePath)
    cb(null, filePath)
  },
  filename(req, file, cb) {
    console.log('file: ', file)
    const { ext, name } = path.parse(file.originalname)
    const sanitizedFileName = name.replace(/[^a-zA-Z0-9_-]/g, '')
    cb(null, decodeURI(sanitizedFileName + '_' + Date.now() + ext))
  },
})
const upload = multer({
  storage,
  limits: {
    fileSize: maxFileSize,
  },
  fileFilter(req, file, cb) {
    // 这里定义只允许的文件后缀
    const allowedMimes = ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif', 'image/webp']
    const uploadType = req.params.type || req.body.type
    if (allUploadType.includes(uploadType) && allowedMimes.includes(file.mimetype)) {
      cb(null, true) // 允许上传
    } else {
      cb(new Error('img type error'), false) // 禁止上传
    }
  },
})

exports.upload = upload.any()

exports.uploadType = function (isNext) {
  return async (req, res, next) => {
    try {
      let tip = null
      const uploadType = req.params.type || req.body.type
      if (allUploadType.includes(uploadType)) {
        tip = tips[uploadType]
      } else {
        assert(false, 422, '文件上传分类不正确')
      }
      let fileURLS = req.files.map((item) => {
        let { destination, filename } = item
        return path.join(path.parse(destination).name, filename).replace(/\\/g, '/').replace('http:/', 'http://')
      })
      if (isNext) {
        req.imgUrl = fileURLS[0]
        next()
      } else {
        res.success({
          message: tip,
          imgUrl: uploadURL + "/" + fileURLS[0],
        });
      }
    } catch (err) {
      next(err)
    }
  }
}
